package com.pds.web.company.controller;

import com.alibaba.excel.EasyExcel;
import com.pds.common.annotation.Log;
import com.pds.common.core.controller.BaseController;
import com.pds.common.core.domain.R;
import com.pds.common.core.page.TableDataInfo;
import com.pds.common.enums.BusinessType;
import com.pds.common.utils.poi.ExcelUtil;
import com.pds.web.company.domain.PdsCompanyContact;
import com.pds.web.company.excel.CompanyContactExcel;
import com.pds.web.company.excel.CompanyContactListener;
import com.pds.web.company.excel.CompanyContactTemplate;
import com.pds.web.company.service.IPdsCompanyContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 企业用户管理
 */
@RestController
@RequestMapping("/companyContact")
public class PdsCompanyContactController extends BaseController {

    @Autowired
    private IPdsCompanyContactService pdsCompanyContactService;

    /**
     * 新增用户
     *
     * @param pdsCompanyContact
     * @return
     * @throws Exception
     */
    @Log(title = "企业新增用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('company:user:edit')")
    public R addContact(@RequestBody PdsCompanyContact pdsCompanyContact) throws Exception {
        pdsCompanyContactService.addContact(pdsCompanyContact);
        return R.ok();
    }

    /**
     * 修改用户
     *
     * @param pdsCompanyContact
     * @return
     * @throws Exception
     */
    @Log(title = "企业修改用户", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermi('company:user:edit')")
    public R updateContact(@RequestBody PdsCompanyContact pdsCompanyContact) throws Exception {
        pdsCompanyContactService.updateContact(pdsCompanyContact);
        return R.ok();
    }

    /**
     * 查询企业用户列表
     *
     * @param pdsCompanyContact - companyId 企业ID，环保局查询时需要传入
     *                          - name 姓名（查询条件）
     *                          - phone 联系方式（查询条件）
     *                          - idCard 身份证号（查询条件）
     * @return
     * @throws Exception
     */
    @GetMapping("/getUserList")
    public TableDataInfo getCompanyUserList(PdsCompanyContact pdsCompanyContact) {
        startPage();
        List<PdsCompanyContact> list = pdsCompanyContactService.getCompanyUserList(pdsCompanyContact);
        return getDataTable(list);
    }

    /**
     * 查询企业用户详细
     *
     * @param id 主键id
     * @return
     * @throws Exception
     */
    @GetMapping("/getUserInfo")
    public R getUserInfo(@RequestParam("id") Long id) throws Exception {
        PdsCompanyContact pdsCompanyContact = pdsCompanyContactService.getUserInfo(id);
        return R.ok(pdsCompanyContact);
    }

    /**
     * 下载用户批量上传模板
     *
     * @param response
     */
    @GetMapping("/downContactTemplate")
    public void downContactTemplate(HttpServletResponse response) throws Exception {
        String fileName = URLEncoder.encode("企业联系人模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<CompanyContactTemplate> list = new ArrayList<>();
        CompanyContactTemplate template = new CompanyContactTemplate();
        template.setName("示例：张三");
        template.setPhone("122********");
        list.add(template);
        ExcelUtil<CompanyContactTemplate> excelUtil = new ExcelUtil<>(CompanyContactTemplate.class);
        excelUtil.exportExcel(response, list, "企业联系人模板");
    }

    /**
     * 批量新增导入用户
     *
     * @param file
     */
    @Log(title = "企业批量新增导入用户", businessType = BusinessType.INSERT)
    @PostMapping("/importCompanyContact")
//    @PreAuthorize("@ss.hasPermi('company:user:edit')")
    public R<String> importCompanyContact(MultipartFile file, Long companyId) throws Exception {
        //获取文件名+后缀
        String filename = file.getOriginalFilename();
        if (filename != null) {
            //获取其后缀
            String extension = filename.substring(filename.lastIndexOf(".") + 1);
            if (!(extension.equals("xls") || extension.equals("xlsx"))) {
                //此处为自定义异常捕获,可使用其他方式
                throw new RuntimeException("文件格式有误,请检查上传文件格式");
            }
        }
        //获取文件的输入流
        InputStream inputStream = file.getInputStream();
        List<CompanyContactExcel> list = EasyExcel.read(inputStream) //调用read方法
                //注册自定义监听器，字段校验可以在监听器内实现
                .registerReadListener(new CompanyContactListener())
                .head(CompanyContactExcel.class) //对应导入的实体类
                .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
        Integer count = pdsCompanyContactService.importCompanyContact(list, companyId);
        return R.ok(count + "条联系人数据导入成功");
    }
}
